package com.example.patient.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.common.entity.Collection;
import com.example.common.entity.*;
import com.example.common.enums.PayType;
import com.example.common.support.ApiException;
import com.example.common.support.Result;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.example.common.utils.UIDUtils;
import com.example.patient.dto.req.*;
import com.example.patient.dto.resp.*;
import com.example.patient.feign.FileFeign;
import com.example.patient.jpa.*;
import com.example.patient.mapper.DoctorMapper;
import com.example.patient.properties.WxProp;
import com.example.patient.service.DoctorService;
import com.example.patient.utils.PatientUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wxy
 * @Date 2021/1/18 13:40
 * @Version 1.0
 */
@Service
public class DoctorServiceImpl implements DoctorService {
    @Resource
    private DoctorMapper doctorMapper;
    @Resource
    private FileFeign fileFeign;
    @Resource
    private UIDUtils uidUtils;
    @Resource
    private WxProp wxProp;

    @Resource
    private HospitalDepartmentRepository hospitalDepartmentRepository;
    @Resource
    private EnumConfigRepository enumConfigRepository;
    @Resource
    private DoctorBaseInfoRepository doctorBaseInfoRepository;
    @Resource
    private ConfigRepository configRepository;
    @Resource
    private ExInfoRepository exInfoRepository;
    @Resource
    private DoctorNoticeRepository doctorNoticeRepository;
    @Resource
    private CollectionRepository collectionRepository;
    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private HospitalConfigRepository hospitalConfigRepository;
    @Resource
    private CMSRepository cmsRepository;
    @Resource
    private ClientPatientsInfoRepository clientPatientsInfoRepository;
    @Resource
    private OnlineConsultationRepository onlineConsultationRepository;
    @Resource
    private PatientsInfoRepository patientsInfoRepository;
    @Resource
    private ImgRepository imgRepository;
    @Resource
    private OrderMainRepository orderMainRepository;
    @Resource
    private ClientBaseInfoRepository clientBaseInfoRepository;
    @Resource
    private PlantOrderRepository plantOrderRepository;
    

    /**
     * 查询初始筛选项
     */
    @Override
    public FilterItemResp FilterItem(FilterItemReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Integer pType = CheckUtils.checkNullReturn(req.getPType(), new ApiException(1, "类型不能为空"));

        List<HospitalDepartment> departmentList = hospitalDepartmentRepository.findByDisableAndIsRecommendAndPdId(Boolean.FALSE,Boolean.TRUE,0L);
        List<FilterItemResp.FilterItemDepResp> deptList = departmentList.stream().map(m -> {
            FilterItemResp.FilterItemDepResp depResp = new FilterItemResp.FilterItemDepResp();
            depResp.setId(m.getId());
            depResp.setName(m.getName());
            return depResp;
        }).collect(Collectors.toList());

        List<EnumConfig> enumConfigList = enumConfigRepository.findByDisableAndTypeIn(Boolean.FALSE, Arrays.asList(1, 2));
        List<FilterItemResp.FilterItemServiceResp> sType = new ArrayList<>();
        switch (pType) {
            case 1:
                sType = enumConfigList.stream()
                        .filter(f -> 2 == f.getType() && !"10".equals(f.getCode()))
                        .map(m -> {
                            FilterItemResp.FilterItemServiceResp serviceResp = new FilterItemResp.FilterItemServiceResp();
                            serviceResp.setCode(m.getCode());
                            serviceResp.setName(m.getName());
                            return serviceResp;
                        })
                        .collect(Collectors.toList());
                break;
            case 3:
                sType = enumConfigList.stream()
                        .filter(f -> 2 == f.getType() && "10".equals(f.getCode()))
                        .map(m -> {
                            FilterItemResp.FilterItemServiceResp serviceResp = new FilterItemResp.FilterItemServiceResp();
                            serviceResp.setCode(m.getCode());
                            serviceResp.setName(m.getName());
                            return serviceResp;
                        })
                        .collect(Collectors.toList());
                break;
            case 2:
            default:
                break;
        }

        List<String> names = enumConfigList.stream().filter(f -> 1 == f.getType()).map(EnumConfig::getName).collect(Collectors.toList());

        FilterItemResp resp = new FilterItemResp();
        resp.setDep(deptList);
        resp.setTitle(names);
        resp.setService(sType);
        return resp;
    }

    /**
     * 下级科室
     */
    @Override
    public GetCDepResp GetCDep(GetCDepReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long pdId = CheckUtils.checkNullReturn(req.getPDID(), new ApiException(1, "父级id不能为空"));

        List<GetCDepResp.GetCDepDepResp> dep =
                hospitalDepartmentRepository.findByDisableAndPdId(Boolean.FALSE, pdId)
                        .stream()
                        .map(m -> {
                            GetCDepResp.GetCDepDepResp resp = new GetCDepResp.GetCDepDepResp();
                            resp.setId(m.getId());
                            resp.setName(m.getName());
                            return resp;
                        })
                        .collect(Collectors.toList());

        GetCDepResp resp = new GetCDepResp();
        resp.setDep(dep);
        return resp;
    }

    /**
     * 筛选医生
     */
    @Override
    public PageInfo<DoctorListResp> DoctorList(DoctorListReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Integer pageNumber = CheckUtils.checkNullReturn(req.getPage(), new ApiException(1, "分页页数不能为空"));
        Integer pageSize = CheckUtils.checkNullReturn(req.getLimit(), new ApiException(1, "分页条数不能为空"));

        String title = req.getTitle();
        Long depId = req.getDepID();
        String service = req.getService();
        String searchName = req.getSearchName();
        return PageHelper
                .startPage(pageNumber, pageSize)
                .doSelectPageInfo(() -> doctorMapper.findDoctorByCondition(title, depId, service, searchName));
    }

    /**
     * 医生详情
     */
    @Override
    public DetailResp Detail(DetailReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long doctorId = CheckUtils.checkNullReturn(req.getDCID(), new ApiException(1, "医生id不能为空"));

        DoctorBaseInfo doctorInfo = doctorBaseInfoRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "没有医生信息"));
        HospitalDepartment department = hospitalDepartmentRepository.findById(doctorInfo.getDepartId()).orElseThrow(() -> new ApiException(1, "没有科室信息"));
        Config doctorConfig = configRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "医生信息不全"));
        ExInfo doctorExInfo = exInfoRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "医生信息不全"));

        DoctorNotice notice = doctorNoticeRepository.findTopByDcIdOrderByCreateTimeDesc(doctorId);
        String noticeStr = null == notice ? "" : notice.getContents_nvarchar();

        Long count = collectionRepository.countByDcIdAndClientId(doctorId, uidUtils.getUid());
        Boolean isCollection = count > 0 ? Boolean.TRUE : Boolean.FALSE;

        Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
        CheckUtils.checkNull(hospital, new ApiException(1, "没有医院"));
        HospitalConfig hospitalConfig = hospitalConfigRepository.findById(hospital.getId()).orElseThrow(() -> new ApiException(1, "没有医院配置"));

        List<CMS> cmsList = cmsRepository.findByTypesIn(Arrays.asList(10, 11, 12, 13));

        List<DetailResp.InquiryServiceResp> ruleList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(cmsList)) {
            cmsList.forEach(c -> {
                DetailResp.InquiryServiceResp inquiryServiceResp = new DetailResp.InquiryServiceResp();
                switch (c.getTypes()) {
                    case 10:
                        inquiryServiceResp.setAType(c.getTypes());
                        inquiryServiceResp.setIsOpen(hospitalConfig.getNetConfig() && doctorConfig.getNetReferral());
                        inquiryServiceResp.setPrice(doctorConfig.getReferralPrice());
                        inquiryServiceResp.setRule(String.format(c.getNContent(), doctorConfig.getReferralValid() / 60));
                        inquiryServiceResp.setValid(doctorConfig.getReferralValid());
                        ruleList.add(inquiryServiceResp);
                        break;
                    case 11:
                        inquiryServiceResp.setAType(c.getTypes());
                        inquiryServiceResp.setIsOpen(hospitalConfig.getImgText() && doctorConfig.getImgText());
                        inquiryServiceResp.setPrice(doctorConfig.getImgTextPrice());
                        inquiryServiceResp.setRule(String.format(c.getNContent(), doctorConfig.getImgTextValid() / 60));
                        inquiryServiceResp.setValid(doctorConfig.getImgTextValid());
                        ruleList.add(inquiryServiceResp);
                        break;
                    case 12:
                        inquiryServiceResp.setAType(c.getTypes());
                        inquiryServiceResp.setIsOpen(hospitalConfig.getPhone() && doctorConfig.getPhone());
                        inquiryServiceResp.setPrice(doctorConfig.getPhonePrice());
                        inquiryServiceResp.setRule(String.format(c.getNContent(), doctorConfig.getPhoneValid()));
                        inquiryServiceResp.setValid(doctorConfig.getPhoneValid());
                        ruleList.add(inquiryServiceResp);
                        break;
                    case 13:
                        inquiryServiceResp.setAType(c.getTypes());
                        inquiryServiceResp.setIsOpen(hospitalConfig.getVideo() && doctorConfig.getVideo());
                        inquiryServiceResp.setPrice(doctorConfig.getVideoPrice());
                        inquiryServiceResp.setRule(String.format(c.getNContent(), doctorConfig.getVideoValid()));
                        inquiryServiceResp.setValid(doctorConfig.getVideoValid());
                        ruleList.add(inquiryServiceResp);
                        break;
                    default:
                        break;
                }
            });
        }

        List<DetailResp.CommentResp> commentRespList = new ArrayList<>();
        List<Map<String, Object>> mapList = doctorMapper.findDetailRespCommentResp(doctorId,(req.getPage()-1)*req.getLimit(),req.getLimit());
        Long total = doctorMapper.countDetailRespCommentResp(doctorId);
        if (!CollectionUtils.isEmpty(mapList)) {
            commentRespList = mapList.stream().map(m -> {
                String re = m.get("re") != null ? m.get("re").toString() : "";
                String name = m.get("name").toString();
                String dScore = m.get("dScore").toString();
                String dRemark = m.get("dRemark").toString();
                String createTime = m.get("createTime").toString();

                DetailResp.CommentResp resp = new DetailResp.CommentResp();
                resp.setRe(re);
                resp.setName(PatientUtils.getString(name));
                resp.setDScore(dScore);
                resp.setDRemark(dRemark);
                resp.setCreateTime(createTime);
                return resp;
            }).collect(Collectors.toList());
        }
        // TODO: 2021/1/19  BInquiry bInquiry = new BInquiry();
        // TODO: 2021/1/19  bInquiry.FinInquiry(db,UID,id);
        // TODO: 2021/1/19  bInquiry.FinToBeReceive(db, UID, id);
        
        boolean isPlantOrder = hospital.getIsPlantOrder();
        List<DetailResp.Plant> plantList = null;
        if(isPlantOrder){
            plantList = new ArrayList<>();
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                now = format.parse(format.format(now));
            } catch (Exception e) {
                //TODO: handle exception
            }
            Calendar ca = Calendar.getInstance();
            ca.setTime(now);
            ca.add(Calendar.DAY_OF_MONTH, 6);
            Date end = ca.getTime();        
            List<PlantOrder> list = plantOrderRepository.findDoctorPlant(doctorId,now, end);
            Map<Date, List<PlantOrder>> dateList = list.stream().collect(Collectors.groupingBy(PlantOrder::getPlantTime));
            for(Map.Entry<Date, List<PlantOrder>> entry : dateList.entrySet()){
                Date mapKey = entry.getKey();
                List<PlantOrder> mapValue = entry.getValue();
                DetailResp.Plant onePlant = new DetailResp.Plant();
                onePlant.setPlantTime(mapKey);
                List<DetailResp.Plant.PlantOneDay> oneDayList = new ArrayList<>();
                for(PlantOrder p : mapValue){
                    DetailResp.Plant.PlantOneDay one = new DetailResp.Plant.PlantOneDay();
                    one.setTimeType(p.getTimeType());
                    one.setTimeTypeName(p.getTimeType() == 1 ? "上午" : p.getTimeType() == 2 ? "下午" : p.getTimeType() == 3 ? "晚间" : "");
                    one.setStartTime(p.getStartTime());
                    one.setEndTime(p.getEndTime());
                    one.setCountOrder(p.getCountOrder());
                    one.setLastOrder(p.getCountOrder() > 0 ? p.getCountOrder() - p.getSellCount() : 0);
                    oneDayList.add(one);
                }
                onePlant.setOneDayList(oneDayList);
                plantList.add(onePlant);
            }
        }

        DetailResp resp = new DetailResp();
        resp.setName(doctorInfo.getName());
        resp.setTitle(doctorInfo.getTitle());
        resp.setDName(department.getName());
        resp.setHead(doctorInfo.getHead());
        resp.setReceive(doctorExInfo.getReceive());
        resp.setPraise(doctorExInfo.getPraise());
        resp.setInquiry(doctorExInfo.getInquiry());
        resp.setIsCollection(isCollection);
        resp.setIntro(doctorInfo.getIntro());
        resp.setProfessionScope(doctorInfo.getProfessionScope());
        resp.setCertificateCode(doctorInfo.getCertificateCode());
        resp.setNotice(noticeStr);
        resp.setComment(commentRespList);
        resp.setInquiryService(ruleList);
        resp.setIsPlant(isPlantOrder);
        resp.setPlantList(plantList);
        resp.setTotal(total);
        return resp;
    }

    /**
     * 关注、取消关注 医生
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public DoCollectionResp DoCollection(DoCollectionReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long doctorId = CheckUtils.checkNullReturn(req.getDCID(), new ApiException(1, "医生id不能为空"));
        Boolean isCollection = CheckUtils.checkNullReturn(req.getIsCollection(), new ApiException(1, "标识不能为空"));

        if (isCollection) {
            Collection collection = new Collection();
            collection.setDcId(doctorId);
            collection.setClientId(uidUtils.getUid());
            collection.setCreateTime(new Date());
            collection.setSeed(Boolean.FALSE);
            collectionRepository.save(collection);
        } else {
            Collection collection = collectionRepository.findByDcIdAndClientId(doctorId, uidUtils.getUid());
            if (!ObjectUtils.isEmpty(collection)) {
                collectionRepository.delete(collection);
            }
        }
        DoCollectionResp resp = new DoCollectionResp();
        resp.setSave(Boolean.TRUE);
        return resp;
    }

    /**
     * 就诊信息
     */
    @Override
    public VisitInfoResp VisitInfo(VisitInfoReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long doctorId = CheckUtils.checkNullReturn(req.getDCID(), new ApiException(1, "医生id不能为空"));
        Integer aType = CheckUtils.checkNullReturn(req.getAType(), new ApiException(1, "问诊类型不能为空"));

        DoctorBaseInfo doctorInfo = doctorBaseInfoRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "没有医生信息"));
        HospitalDepartment department = hospitalDepartmentRepository.findById(doctorInfo.getDepartId()).orElseThrow(() -> new ApiException(1, "没有科室信息"));
        Config doctorConfig = configRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "医生信息不全"));

        EnumConfig enumConfig = enumConfigRepository.findById(aType.toString()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        String aName = enumConfig.getName();

        CMS cms = cmsRepository.findByTypes(3);
        CheckUtils.checkNull(cms, new ApiException(1, "未查询到数据"));
        String protocol = cms.getNContent();

        BigDecimal price = new BigDecimal(0);
        switch (aType) {
            case 10:
                price = doctorConfig.getReferralPrice();
                break;
            case 11:
                price = doctorConfig.getImgTextPrice();
                break;
            case 12:
                price = doctorConfig.getPhonePrice();
                break;
            case 13:
                price = doctorConfig.getVideoPrice();
                break;
            default:
                break;
        }
        VisitInfoResp.DocInfoResp docInfoResp = new VisitInfoResp.DocInfoResp();
        docInfoResp.setName(doctorInfo.getName());
        docInfoResp.setHead(doctorInfo.getHead());
        docInfoResp.setTitle(doctorInfo.getTitle());
        docInfoResp.setDName(department.getName());
        docInfoResp.setAName(aName);
        docInfoResp.setPrice(price);
        docInfoResp.setProtocol(protocol);

        VisitInfoResp.PatientResp patientResp = new VisitInfoResp.PatientResp();
        ClientPatientsInfo patientsInfo = clientPatientsInfoRepository.findFirstByClientIDAndDefaultBitAndDisable(uidUtils.getUid(), Boolean.TRUE, Boolean.FALSE);
        if (!ObjectUtils.isEmpty(patientsInfo)) {
            patientResp.setPid(patientsInfo.getPid());
            patientResp.setName(patientsInfo.getName());
            patientResp.setSex(patientsInfo.getSex());
            List<Map<String, Object>> mapList = doctorMapper.findVisitInfoRespPatientResp(patientsInfo.getPid());
            if (!CollectionUtils.isEmpty(mapList)) {
                Map<String, Object> map = mapList.get(0);
                String allergy = null == map.get("Allergy") ? "" : map.get("Allergy").toString();
                String pastDisease = null == map.get("PastDisease") ? "" : map.get("PastDisease").toString();
                patientResp.setAllergy(allergy);
                patientResp.setPastDisease(pastDisease);
            }
        }

        VisitInfoResp resp = new VisitInfoResp();
        resp.setDocInfo(docInfoResp);
        resp.setPatient(patientResp);
        return resp;
    }

    /**
     * 上传文件
     */
    @Override
    public Object VisitUpLoad(MultipartFile file) {
        CheckUtils.checkNull(file, new ApiException(1, "文件不能为空"));
        Result<Object> result = fileFeign.updateFile(file);
        return result.getData();
    }

    /**
     * 是否存在有效问诊
     */
    @Override
    public HaveInquiryResp HaveInquiry(HaveInquiryReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long doctorId = CheckUtils.checkNullReturn(req.getDCID(), new ApiException(1, "医生id不能为空"));
        Long patientId = CheckUtils.checkNullReturn(req.getPID(), new ApiException(1, "患者id不能为空"));

        Long count = onlineConsultationRepository.countByDcIdAndPidAndOcStatusIn(doctorId, patientId, Arrays.asList(0, 1));
        Boolean have = 0 == count ? Boolean.FALSE : Boolean.TRUE;

        HaveInquiryResp resp = new HaveInquiryResp();
        resp.setHave(have);
        return resp;
    }

    /**
     * 提交就诊信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public VisitResp Visit(VisitReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Integer aType = req.getAType();
        Integer first = req.getFirst();
        Long pid = req.getPID();
        String chiefComplaint = req.getChiefcomplaint();
        String allergy = req.getAllergy();
        String pastDisease = req.getPastDisease();
        Date fVisitDate = req.getFVisitDate();
        String fHospital = req.getFHospital();
        String fDepartment = req.getFDepartment();
        String fDiagnosis = req.getFDiagnosis();
        List<String> images = req.getImgs();

        ClientPatientsInfo clientPatientsInfo = clientPatientsInfoRepository.findById(pid).orElseThrow(() -> new ApiException(1, "未找到患者信息"));

        Long id = IdUtils.generateId();
        long age = DateUtil.betweenYear(clientPatientsInfo.getBirthday(), new Date(), Boolean.FALSE);

        PatientsInfo orderPatientsInfo = new PatientsInfo();
        orderPatientsInfo.setId(id);
        orderPatientsInfo.setName(clientPatientsInfo.getName());
        orderPatientsInfo.setAge((int) age);
        orderPatientsInfo.setSex(clientPatientsInfo.getSex());
        orderPatientsInfo.setAType(aType);
        orderPatientsInfo.setFirst(first);
        orderPatientsInfo.setPid(pid);
        orderPatientsInfo.setChiefComplaint(chiefComplaint);
        orderPatientsInfo.setAllergy(allergy);
        orderPatientsInfo.setPastDisease(pastDisease);
        orderPatientsInfo.setFVisitDate(fVisitDate);
        orderPatientsInfo.setFHospital(fHospital);
        orderPatientsInfo.setFDepartment(fDepartment);
        orderPatientsInfo.setFDiagnosis(fDiagnosis);
        orderPatientsInfo.setIsPregnancy(req.getIsPregnancy());
        orderPatientsInfo.setIsLactationPeriod(req.getIsLactationPeriod());
        patientsInfoRepository.save(orderPatientsInfo);

        List<Img> imgList = images.stream().map(m -> {
            Img img = new Img();
            img.setId(IdUtils.generateId());
            img.setImg(m);
            img.setPatientsInfoId(id);
            img.setCreateTime(new Date());
            return img;
        }).collect(Collectors.toList());
        imgRepository.saveAll(imgList);

        VisitResp resp = new VisitResp();
        resp.setPatientsInfoId(id);
        return resp;
    }

    /**
     * 创建问诊订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public CreateOrderResp CreateOrder(CreateOrderReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long doctorId = CheckUtils.checkNullReturn(req.getDCID(), new ApiException(1, "医生ID不能为空"));
        Long patientId = CheckUtils.checkNullReturn(req.getPID(), new ApiException(1, "患者ID不能为空"));
        Integer payType = CheckUtils.checkNullReturn(req.getPayType(), new ApiException(1, "支付方式不能为空"));
        Integer aType = CheckUtils.checkNullReturn(req.getAType(), new ApiException(1, "问诊类型不能为空"));
        Long patientsInfoID = CheckUtils.checkNullReturn(req.getPatientsInfoID(), new ApiException(1, "就诊ID不能为空"));

        Long count = orderMainRepository.countByPatientsInfoID(patientsInfoID);
        if (count > 0) {
            throw new ApiException(1, "就诊信息已使用，创建就诊订单失败");
        }

        String id = "MP" + IdUtils.generateId();
        Long uid = uidUtils.getUid();

        BigDecimal askMoney = new BigDecimal(0);
        Config doctorConfig = configRepository.findById(doctorId).orElseThrow(() -> new ApiException(1, "未查询到医生配置"));
        switch (aType) {
            case 13:
                askMoney = doctorConfig.getVideoPrice();
                break;
            case 12:
                askMoney = doctorConfig.getPhonePrice();
                break;
            case 11:
                askMoney = doctorConfig.getImgTextPrice();
                break;
            case 10:
                askMoney = doctorConfig.getReferralPrice();
                break;
            default:
                break;
        }

        String payUrl = "";
        if (2 == payType) {
            payUrl = String.format(wxProp.getPayUrl(), id, "1") + "&wapay=" + req.getPayPort();
        }

        Collection collection = collectionRepository.findByDcIdAndClientId(doctorId, uid);
        if (ObjectUtils.isEmpty(collection)) {
            // 问过诊默认关注。
            collection = new Collection();
            collection.setSeed(Boolean.TRUE);
            collection.setDcId(doctorId);
            collection.setClientId(uid);
            collection.setCreateTime(new Date());
            collectionRepository.save(collection);
        }

        PatientsInfo orderPatientsInfo = patientsInfoRepository.findById(patientsInfoID).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        orderPatientsInfo.setOrderNo(id);
        patientsInfoRepository.save(orderPatientsInfo);

        OrderMain orderMain = new OrderMain();
        orderMain.setOrderNo(id);
        orderMain.setClientID(uid);
        orderMain.setPid(patientId);
        orderMain.setDcId(doctorId);
        orderMain.setSystemStatus(1L);
        orderMain.setPayType(payType);
        orderMain.setCreateTime(new Date());
        orderMain.setAskMoney(askMoney);
        orderMain.setAType(aType);
        orderMain.setOcStatus(0);
        orderMain.setPatientsInfoID(patientsInfoID);
        boolean isPlant = req.getIsPlantOrder() != null && req.getIsPlantOrder();
        orderMain.setIsPlantOrder(isPlant);
        if(isPlant){
            PlantOrder plant =  plantOrderRepository.findOneDoctorPlant(doctorId,req.getPlant(),req.getTimeType());
            if(plant == null)
                throw new ApiException(1, "医生没有排班"); 
            orderMain.setPlantDate(req.getPlant());
            orderMain.setTimeType(req.getTimeType());
            orderMain.setPlantPeriod((req.getTimeType() == 1 ? "上午" : req.getTimeType() == 2 ? "下午" : req.getTimeType() == 3 ? "晚间" : "") + 
                " " + plant.getStartTime() + "-" + plant.getEndTime());
        }
        orderMainRepository.save(orderMain);

        CreateOrderResp resp = new CreateOrderResp();
        resp.setOrderNO(id);
        resp.setPayUrl(payUrl);
        return resp;
    }

    /**
     * 支付完成
     */
    @Override
    public DoctorPayCompletionResp PayCompletion(PayCompletionReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String orderNo = CheckUtils.checkNullReturn(req.getOrderNO(), new ApiException(1, "订单号不能为空"));

        OrderMain orderMain = orderMainRepository.findById(orderNo).orElseThrow(() -> new ApiException(1, "订单不存在"));
        Boolean isPay = !StringUtils.isEmpty(orderMain.getTransactionID()) ? Boolean.TRUE : Boolean.FALSE;

        EnumConfig sysEnumConfig = enumConfigRepository.findById(orderMain.getAType().toString()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        DoctorBaseInfo doctorBaseInfo = doctorBaseInfoRepository.findById(orderMain.getDcId()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        ClientPatientsInfo clientPatientsInfo = clientPatientsInfoRepository.findById(orderMain.getPid()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        PatientsInfo orderPatientsInfo = patientsInfoRepository.findById(orderMain.getPatientsInfoID()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        ClientBaseInfo clientBaseInfo = clientBaseInfoRepository.findById(clientPatientsInfo.getClientID()).orElseThrow(() -> new ApiException(1, "未查询到数据"));

        String pName = PayType.valueToDesc(orderMain.getPayType());

        DoctorPayCompletionResp resp = new DoctorPayCompletionResp();
        resp.setIsPay(isPay);
        resp.setSName(sysEnumConfig.getName());
        resp.setDName(doctorBaseInfo.getName());
        resp.setPName(clientPatientsInfo.getName());
        resp.setSex(clientPatientsInfo.getSex());
        resp.setAge(orderPatientsInfo.getAge());
        resp.setPayPrice(orderMain.getAskMoney());
        resp.setPayTypeName(pName);
        resp.setPayTime(orderMain.getOrderPayTime());
        resp.setOpenId(clientBaseInfo.getOpenId());
        resp.setOcId(orderMain.getOcId());
        resp.setAType(orderMain.getAType());
        resp.setChiefComplaint(orderPatientsInfo.getChiefComplaint());
        return resp;
    }
}
